import { Ref } from "vue";
import { ILink, LinkType, type } from "@/components/hrefSelector/types";

export function useHrefSelector() {
  const linkFormVisible: Ref<boolean> = ref(false);
  let linkIndex = ref(0);

  /**
   * 用于链接选择器回显
   */
  const linkObject: Ref<ILink> = ref({
    urlName: "",
    urlType: <type>"manual",
    linkType: <LinkType>"href",
    url: "",
  });

  /**
   * 显示对话框
   * @param targetAssignObject 操作中的对象，例如config.pageConfig.imgList[linkIndex]
   * @param idx 操作对象的index
   */
  const linkDialog = (targetAssignObject: any, idx: number) => {
    linkIndex.value = idx;
    linkObject.value.urlName = targetAssignObject.urlName;
    linkObject.value.url = targetAssignObject.url;
    linkObject.value.urlType = targetAssignObject.urlType;
    linkObject.value.linkType = targetAssignObject.linkType;
    linkFormVisible.value = true;
  };

  /**
   * 对话确定后的操作
   * @param link 链接选择器提供的链接对象
   * @param targetAssignObject 被赋值的对象，例如：config.pageConfig.imgList[linkIndex]
   */
  const submitUrl = (link: ILink, targetAssignObject: any) => {
    targetAssignObject.url = link.url;
    targetAssignObject.urlName = link.urlName;
    targetAssignObject.urlType = link.urlType;
    targetAssignObject.linkType = link.linkType;
    linkFormVisible.value = false;
  };

  return {
    linkFormVisible,
    linkIndex,
    linkObject,
    linkDialog,
    submitUrl,
  };
}
